const {DealObject} = require("./deal-props-parser");
const {JSDOM} = require("jsdom");
const {ClientEventClickAttributes} = require("../enums");


function extractInfo(element) {
    const info = {};

    const id = element.getAttribute('ID');
    if (id) info.ID = id;

    const text = element.getAttribute('Text');
    if (text && !text.includes('<%# Bind')) {
        info.TitleInDOM = text;
    }

    const dom = new JSDOM(element.outerHTML);

    // Находим элемент, содержащий ClientSideEvents (пока если только он обвернут element)
    const clientEventsElement = dom.window.document.querySelector('clientsideevents');
    if (clientEventsElement && clientEventsElement.attributes) {
        ClientEventClickAttributes.forEach(attr => {
            const value = clientEventsElement.getAttribute(attr)
            if (value) {
                info[attr] = value
            }
        })
    }


    const binds = [];
    element.getAttributeNames().forEach(attr => {
        const match = element.getAttribute(attr).match(/<%# Bind\("([^"]+)"\) %>/);
        if (match) {
            if (DealObject[match[1]]) {
                binds.push(match[1] + ' (Объект_сделки)');
            } else {
                binds.push(match[1] + '');
            }

        }
    });
    if (binds.length > 0) info.bind = binds.join(',');

    const tagName = element.tagName.toLowerCase();
    info.Entity = tagName.includes(':') ? tagName.split(':')[1] : tagName;


    return info;
}

module.exports = {extractInfo}